﻿using DongFangGuoKai.TaskPlatform.Commn.ConfigureOptions;
using DongFangGuoKai.TaskPlatform.Config;
using DongFangGuoKai.TaskPlatform.Domain;
using Microsoft.Extensions.Options;
using SqlSugar;

namespace DongFangGuoKai.TaskPlatform.WebApi.Utility
{
    /// <summary>
    /// 后台服务
    /// https://learn.microsoft.com/zh-cn/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-8.0&tabs=visual-studio-mac%2Cvisual-studio
    /// </summary>
    public class CtmBackgroundService : BackgroundService
    {

        private readonly IServiceScopeFactory _scopeFactory;
        private readonly IServiceScope _serviceScope;

        public CtmBackgroundService(IServiceScopeFactory scopeFactory)
        {
            _scopeFactory = scopeFactory;
            //通过这个注入服务
            _serviceScope = _scopeFactory.CreateScope();
        }
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            //检查数据库表是否存在并初始化
            InitInfo();

            //检查appsetings配置是否配置
            CheckInfo();

            //启动服务
            StartInfo();

            await Task.CompletedTask;
        }

        /// <summary>
        /// 检查配置信息
        /// </summary>
        /// <exception cref="Exception"></exception>
        private void CheckInfo()
        {
            //检查Token配置信息
            var tokenConfigOption = _serviceScope.ServiceProvider.GetService<IOptions<TokenConfigOption>>().Value;
            if (tokenConfigOption == null)
            {
                throw new Exception("未配置TokenConfigOption");
            }

            //检查Url请求是否配置
            var urlConfigOption = _serviceScope.ServiceProvider.GetService<IOptions<UrlConfigOption>>().Value;
            if (urlConfigOption == null)
            {
                throw new Exception("未配置UrlConfigOption");
            }


        }

        /// <summary>
        /// 初始化表结构
        /// </summary>
        private void InitInfo()
        {
            var client = _serviceScope.ServiceProvider.GetRequiredService<ISqlSugarClient>();

            List<Type> types = new List<Type>();
            types.Add(typeof(SyncTaskIEntity));

            var tables = string.Join(',', types.Select(x => "'" + x.Name + "'").ToArray());
            var sql = $"Select count(1) from  sys.tables where name in  ({tables})";
            if (client.Ado.GetInt(sql) <= 0)
            {
                client.CodeFirst
                       .SetStringDefaultLength(200)
                       .InitTables(types.ToArray());
            }


        }

        /// <summary>
        /// 初始化服务
        /// </summary>
        private void StartInfo()
        {
            //默认初始化Scheduler
            SchedulerCenter? schedulerCenter = _serviceScope.ServiceProvider.GetService<SchedulerCenter>();
        }

        /// <summary>
        /// 周期性服务作业
        /// </summary>
        /// <param name="stoppingToken"></param>
        private Task BackgroundService(CancellationToken stoppingToken)
        {
            Console.WriteLine("托管服务开始.....");
            return Task.Factory.StartNew(async () =>
            {
                //周期性作用   
                int stopCount = 0;
                while (!stoppingToken.IsCancellationRequested)
                {
                    try
                    {
                        Console.WriteLine(DateTime.Now);
                        throw new Exception("测试服务");
                    }
                    catch (Exception ex)
                    {
                        stopCount++;

                        Console.WriteLine("异常服务次数:" + stopCount);
                        if (stopCount >= 10)
                        {
                            base.StopAsync(stoppingToken);
                            Console.WriteLine("服务终止");
                        }
                    }
                    await Task.Delay(5000, stoppingToken);
                }
            }, stoppingToken);


        }



        public override void Dispose()
        {
            base.Dispose();
            _serviceScope.Dispose();
        }



    }
}
